package com.hzy.system.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzy.infrastructure.Tools;
import com.hzy.infrastructure.domain.vo.PagingVo;
import com.hzy.infrastructure.exception.MessageBox;
import com.hzy.system.domain.SysRole;
import com.hzy.system.domain.SysUserRole;
import com.hzy.system.mapper.ISysRoleMapper;
import com.hzy.system.service.ISysRoleService;
import com.hzy.system.service.ISysUserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hzy
 * @since 2020-04-28
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<ISysRoleMapper, SysRole> implements ISysRoleService {
    private final ISysUserRoleService userRoleService;

    public SysRoleServiceImpl(ISysUserRoleService userRoleService) {
        this.userRoleService = userRoleService;
    }

    @Override
    public PagingVo<Map<String, Object>> findList(Integer page, Integer size, SysRole search) {
        Page<Map<String, Object>> iPage = new Page<>(page, size);
        List<Map<String, Object>> data = this.baseMapper.getList(iPage, search);
        return PagingVo.page(iPage, data);
    }

    @Override
    public Map<String, Object> findForm(String id) {
        Map<String, Object> map = new HashMap<>(2);

        SysRole form = this.baseMapper.selectById(id);
        form = Tools.nullSafe(form, new SysRole());

        if (ObjectUtils.isEmpty(id)) {
            Integer maxNumber = this.baseMapper.getMaxNumber();
            form.setNumber((ObjectUtils.isEmpty(maxNumber) ? 0 : maxNumber) + 1);
        }

        map.put("id", id);
        map.put("form", form);
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveForm(SysRole form) {
        this.saveOrUpdate(form);
        return form.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteList(List<String> ids) {
        // 查看该信息能否删除
        long count = this.lambdaQuery().in(SysRole::getId, ids).eq(SysRole::getIsDelete, 0).count();
        if (count > 0) {
            MessageBox.show("信息不能删除!");
        }
        this.removeByIds(ids);
        this.userRoleService.lambdaUpdate().in(SysUserRole::getRoleId, ids).remove();
    }
}
